<template>
    <view class="home">
        <swiper
            class="swiper" 
            circular 
        >
            <swiper-item>
                <image 
                    src="@/static/banner/banner-1.png" 
                    :draggable="false"
                    mode="scaleToFill"
                    class="swiper-img"
                ></image>
            </swiper-item>
        </swiper>
        <uni-notice-bar 
            show-icon 
            scrollable
            text="8:30到17:30工作时间可自助下单,17:30后至第二天8:30不可下单,请联系人工4008897120" 
        />
        <uni-forms
             :model="formData" 
             ref="form" 
             :rules="rules1" 
             validateTrigger="submit" 
             label-width="150rpx"
             err-show-type='none'
        >
            <view class="box-1">
                <uni-section
                    type="line"
                    title="地址" 
                    sub-title=""
                >
                </uni-section>
                <uni-forms-item
                    name="startingPoint"
                    label="转运起点"
                    required
                >
                    <view class="point-box">
                        <image
                            src="@/static/index/starting-point.png" 
                            :draggable="false"
                            mode="scaleToFill"
                            class="point-img"
                            @click="showPopup1('startingPoint')"
                        ></image>
                        <uni-easyinput 
                            v-model="formData.startingPoint"
                            type="text" 
                            prefixIcon="location-filled"
                            required
                            placeholder="请输入转运起点" 
                        />
                    </view>
                </uni-forms-item>
                <uni-forms-item
                    name="endingPoint"
                    label="转运终点"
                    required
                >
                    <view class="point-box">
                        <image
                            src="@/static/index/ending-point.png" 
                            :draggable="false"
                            mode="scaleToFill"
                            class="point-img"
                            @click="showPopup1('endingPoint')"
                        ></image>
                        <uni-easyinput
                            v-model="formData.endingPoint"
                            type="text" 
                            prefixIcon="location-filled"
                            placeholder="请输入转运终点" 
                        />
                    </view>
                </uni-forms-item>
            </view>
            <!-- <view class="box-1">
                <uni-section
                    type="line"
                    title="地址" 
                    sub-title=""
                >
                </uni-section>
                <view 
                    class="point-box"
                    @click="showPopup1"
                >
                    <image
                        src="@/static/index/starting-point.png" 
                        :draggable="false"
                        mode="scaleToFill"
                        class="point-img"
                    ></image>
                    <view class="point-box-text-1">庆春东路1号楼</view>
                </view>
                <view 
                    class="point-box"
                    style="margin-top: 20rpx;"
                >
                    <image
                        src="@/static/index/ending-point.png" 
                        :draggable="false"
                        mode="scaleToFill"
                        class="point-img"
                    ></image>
                    <view class="point-box-text-1">庆春东路1号楼</view>
                </view>
            </view> -->
            <view class="box-1">
                <uni-section
                    type="line"
                    title="人员信息" 
                    sub-title=""
                >
                </uni-section>
                <uni-forms-item
                    name="fracture"
                    label="是否骨折"
                    required
                >
                    <uni-data-select
                        v-model="formData.fracture"
                        :localdata="fractureRange"
                        placeholder="请选择是否骨折"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item
                    name="severeDisease"
                    label="是否重症"
                    required
                >
                    <uni-data-select
                        v-model="formData.severeDisease"
                        :localdata="fractureRange"
                        placeholder="请选择是否重症"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item
                    name="section"
                    label="科室"
                    required
                >
                    <uni-data-select
                        v-model="formData.section"
                        :localdata="sectionRange"
                        placeholder="请选择科室"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item
                    name="name"
                    label="姓名"
                    required
                >
                    <uni-easyinput 
                        v-model="formData.name"
                        type="text" 
                        placeholder="请输入姓名" 
                    />
                </uni-forms-item>
                <uni-forms-item
                    name="gender"
                    label="性别"
                    required
                >
                    <uni-data-select
                        v-model="formData.gender"
                        :localdata="genderRange"
                        placeholder="请选择性别"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item
                    name="age"
                    label="年龄"
                    required
                >
                    <uni-easyinput 
                        v-model="formData.age"
                        type="digit" 
                        placeholder="请输入年龄" 
                    />
                </uni-forms-item>
                <uni-forms-item
                    name="weight"
                    label="体重(kg)"
                    required
                >
                    <uni-easyinput 
                        v-model="formData.weight"
                        type="digit" 
                        placeholder="请输入体重(千克)" 
                    />
                </uni-forms-item>
                <uni-forms-item
                    name="peopleNum"
                    label="随车人数"
                    required
                >
                    <uni-easyinput 
                        v-model="formData.peopleNum"
                        type="digit" 
                        placeholder="请输入随车人数" 
                    />
                </uni-forms-item>
                <uni-forms-item
                    name="phone"
                    label="联系电话"
                    required
                >
                    <uni-easyinput 
                        v-model="formData.phone"
                        maxlength="11"
                        type="digit" 
                        placeholder="请输入联系电话" 
                    />
                </uni-forms-item>
                <uni-forms-item
                    name="peoplePhone"
                    maxlength="11"
                    label="紧急联系人电话"
                    required
                >
                    <uni-easyinput 
                        v-model="formData.peoplePhone"
                        type="text" 
                        placeholder="请输入紧急联系人电话" 
                    />
                </uni-forms-item>
                <uni-forms-item
                    name="desc"
                    label="病情描述"
                >
                    <uni-easyinput 
                        v-model="formData.desc"
                        type="textarea" 
                        autoHeight
                        maxlength="500"
                        placeholder="请输入病情描述" 
                    />
                </uni-forms-item>
                <uni-forms-item
                    name="leaveMessage"
                    label="客户留言"
                >
                    <uni-easyinput 
                        v-model="formData.leaveMessage"
                        type="textarea" 
                        autoHeight
                        maxlength="500"
                        placeholder="请输入客户留言" 
                    />
                </uni-forms-item>
            </view>
            <view class="box-1">
                <uni-section
                    type="line"
                    title="用车时间" 
                    sub-title=""
                >
                </uni-section>
                <uni-forms-item
                    name="planStartTime"
                    label="用车时间"
                >
                    <uni-datetime-picker 
                        type="datetime" 
                        v-model="formData.planStartTime"
                        :start="new Date()"
                        placeholder="请选择用车时间"
                    />
                </uni-forms-item>
                <!-- <uni-forms-item
                    name="image"
                    label="设备图片"
                >
                    <uni-file-picker 
                    	v-model="imageValue1" 
                    	file-mediatype="image" 
                        file-extname="png,jpg"
                        limit="1"
                        return-type="object"
                    	mode="grid" 
                        @select="select" 
                    	@delete="delete1" 
                    />
                </uni-forms-item> -->
                <myFilePicker
                    name="image"
                    label="设备图片"
                    v-model="formData.image"
                />
                <!-- <uni-forms-item
                    name="instructions"
                    label="说明书"
                >
                    <uni-file-picker
                    	v-model="myImgArr.instructions" 
                    	file-mediatype="image" 
                        file-extname="png,jpg"
                        limit="9"
                    	mode="grid" 
                        @select="selectImgArr($event, 'myInstructions', 'instructions')" 
                    	@delete="deleteImgArr($event, 'myInstructions', 'instructions')" 
                    />
                </uni-forms-item> -->
                <myFilesPicker 
                    name="instructions"
                    label="说明书"
                    v-model="formData.instructions"
                />
            </view>
            
            <view class="box-1">
                <view class="money-box">
                    <span class="money-span-1">预估费用：</span>
                    <span class="money-span-2">{{formData.money}}元</span>
                </view>
            </view>
            
            <button  
                @click="submit1"
                style="background-color: #000;color: #fff;display: flex;justify-content: center;align-items: center;"
            >
                <image
                    src="@/static/button/car.png" 
                    :draggable="false"
                    mode="scaleToFill"
                    class="button-img"
                ></image>
                <view style="font-weight: bold;">呼叫非紧急转运</view>
            </button>
         </uni-forms>
         <!-- 弹框 -->
         <uni-popup 
            ref="popup" 
            type="center"
        >
            <map 
                :latitude="latitude" 
                :longitude="longitude"
                markers="[]"
            ></map>
         </uni-popup>
    </view>
</template>

<script lang="ts" setup>
    import { onLoad, onShow, onHide, onReady, onUnload } from '@dcloudio/uni-app'
    import { markRaw, onBeforeUnmount, reactive, ref } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { deviceSaveApi } from '@/apis/index'
    import { isPhone } from '@/utils/utils'
    import uploadApi from '@/apis/uploadApi'
    import myFilesPicker from '@/components/myFilesPicker/myFilesPicker.vue'
    import myFilePicker from '@/components/myFilePicker/myFilePicker.vue'
    
    const popup: Ref<any> = ref(null)
    const latitude: Ref<number> = ref(0)
    const longitude: Ref<number> = ref(0)
    const imageValue1: Ref<any> = ref({
    // name: '',
    // extname: '',
    // url: '',
    // path: '',
    })
    
    const myImgArr: any = reactive({
         instructions: [],
         myInstructions: [],   
    })
    // onReady(() => {
        // 获取位置权限
        // uni.authorize({
        //     scope: 'scope.userLocation',
        //     success: () => {
        //         uni.getLocation({
        //         	type: 'gcj02', //返回可以用于uni.openLocation的经纬度
        //         	success: function (res) {
        //                 console.log(res)
        //         		latitude.value = res.latitude;
        //         		longitude.value = res.longitude;
                        
        //         	},
        //             fail: (err) => {
        //             }
        //         });
        //     }
        // })
    // })
    onLoad((val) => {
        // 17:30后至第二天8:30 不可下单 跳出弹窗 提醒请联系人工  联系电话：4008897120
        let hour = new Date().getHours()
        let minute = new Date().getHours()
        if ((hour < 8 || (hour == 8 && minute < 30)) || (hour > 17 || (hour == 17 && minute >= 30))) {
            uni.showModal({
                showCancel: true,
                title: '提示',
                content: '17:30后至第二天8:30不可下单,请联系人工4008897120', 
                success: function (res) {
                    if (res.confirm) {
                    	console.log('用户点击确定');
                        uni.makePhoneCall({
                            phoneNumber: '4008897120'
                        })
                    } else if (res.cancel) {
                    	console.log('用户点击取消');
                    }
                }
            });
        }
    })
    const showPopup1 = (val: string) => {
        // 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
        // popup.value.open()
        // popup.value.close()
        console.log(latitude.value)
        console.log(longitude.value)
        uni.chooseLocation({
            success: (res) => {
                console.log(res)
                formData.value[val] = res.address
            }
        })
        
    }
    
    
    const genderRange: Raw<any[]> = markRaw([
        { value: '男', text: '男' },
        { value: '女', text: '女' },
    ])
    const fractureRange: Raw<any[]> = markRaw([
        { value: '是', text: '是' },
        { value: '否', text: '否' },
    ])
    const sectionRange: Raw<any[]> = markRaw([
        { value: '未知', text: '未知' },
        { value: '发热门诊', text: '发热门诊' },
        { value: '妇科', text: '妇科' },
        { value: '骨科', text: '骨科' },
        { value: '泌尿科', text: '泌尿科' },
        { value: '内科', text: '内科' },
        { value: '神经科', text: '神经科' },
        { value: '外科', text: '外科' },
        { value: '消化科', text: '消化科' },
        { value: '心血管科', text: '心血管科' },
        { value: '心内科', text: '心内科' },
        { value: '脑科', text: '脑科' },
        { value: '产科', text: '产科' },
        { value: '呼吸科', text: '呼吸科' },
        { value: '肿瘤科', text: '肿瘤科' },
    ])
    
    
    const formData: Ref<any> = ref({
        startingPoint: '',
        endingPoint: '',
        name: '',
        gender: '',
        age: '',
        weight: '',
        peopleNum: '',
        phone: '',
        peoplePhone: '',
        desc: '',
        leaveMessage: '',
        fracture: '',
        section: '',
        severeDisease: '',
        planStartTime: '',
        money: 0,
        instructions: [],
        imageValue1: '',
    })
    // setTimeout(() => {
    //     formData.value.instructions = ['fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg', 'fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg']
    // },1000)
    const rules1: any = reactive({
        startingPoint: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入转运起点',
                },
                // {
                //     minLength: 3,
                //     maxLength: 5,
                //     errorMessage: '账号长度在 {minLength} 到 {maxLength} 个字符',
                // },
                // {
                //     validateFunction:function(rule, value, data, callback){
                //         if (value.length < 2) {
                //             callback('请至少勾选两个兴趣爱好')
                //         }
                //         return true
                //     }
                // }
            ],
        },
        endingPoint: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入转运终点',
                },
            ],
        },
        name: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入姓名',
                },
            ],
        },
        gender: {
            rules: [
                {
                    required: true,
                    errorMessage: '请选择性别',
                },
            ],
        },
        age: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入年龄',
                },
            ],
        },
        weight: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入体重(千克)',
                },
            ],
        },
        peopleNum: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入随车人数',
                },
            ],
        },
        phone: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入联系电话',
                },{
                    validateFunction: function(rule, value, data, callback){
                        if (!isPhone(value)) {
                            callback('请输入正确的联系电话')
                        }
                        return true
                    }
                }
            ],
        },
        peoplePhone: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入紧急联系人电话',
                },{
                    validateFunction: function(rule, value, data, callback){
                        if (!isPhone(value)) {
                            callback('请输入正确的联系人电话')
                        }
                        return true
                    }
                }
            ],
        },
        fracture: {
            rules: [
                {
                    required: true,
                    errorMessage: '请选择是否骨折',
                },
            ],
        },
        severeDisease: {
            rules: [
                {
                    required: true,
                    errorMessage: '请选择是否重症',
                },
            ],
        },
        section: {
            rules: [
                {
                    required: true,
                    errorMessage: '请选择科室',
                },
            ],
        },
        planStartTime: {
            rules: [
                {
                    required: true,
                    errorMessage: '请选择用车时间',
                },
            ],
        },
        // instructions: {
        //     rules: [
        //         {
        //             required: true,
        //             errorMessage: '请上传说明书',
        //         },
        //     ],
        // },
    })
    const form: Ref<any> = ref(null)
    // 如果需要使用 validateFunction 自定义校验规则,则不能采用 uni-forms 的 rules 属性来配置校验规则，这时候需要通过ref，在onReady生命周期调用组件的setRules方法绑定验证规则
    onReady(() => {
        form.value.setRules(rules1)
    })
    const submit1 = () => {
       console.log(form.value)
       form.value.validate().then((res: any) => {
           console.log('表单数据信息：', res);
            uni.showModal({
                showCancel: true,
                title: '提示',
                content: '您确认下单吗？',
                success: function (res1) {
                    if (res1.confirm) {
                        console.log('用户点击确定');
                        // 下单成功后，不可直接支付，订单支付进入待支付状态，需要通过人工后台电话联系确认，方可进行支付
                        deviceSaveApi({
                             ...formData.value
                        }).then((res2: any) => {
                            console.log(res2)
                            if (res2.code == 200) {
                                 uni.showModal({
                                     showCancel: false,
                                     title: '提示',
                                     content: res2.msg, //订单已形成 稍后客服人员会与你联系 请保持电话通畅
                                     success: function (res3) {
                                         // uni.redirectTo({
                                         //     url: '/pages/myEquipment/myEquipment'
                                         // });
                                         uni.switchTab({
                                         	url: '/pages/transferOrder/transferOrder'
                                         });
                                         // if (res3.confirm) {
                                         // 	console.log('用户点击确定');
                                         // } else if (res3.cancel) {
                                         // 	console.log('用户点击取消');
                                         // }
                                     }
                                 });
                                 // uni.showToast({
                                 //     title: res2.msg,
                                 //     icon: 'none',
                                 //     mask: true,
                                 // });
                                 // uni.redirectTo({
                                 //     url: '/pages/myEquipment/myEquipment'
                                 // })
                            } else {
                                uni.showToast({
                                     title: res2.msg,
                                     icon: 'error',
                                     mask: true,
                                });
                            }
                        })
                    } else if (res1.cancel) {
                        console.log('用户点击取消');
                    }
               }
            });        
        }).catch((err: any) =>{
            console.log('表单错误信息：', err);
            uni.showToast({
                title: err[0].errorMessage,
                icon: 'error',
                duration: 1500,
                mask: true,
            });
        })
    }
    // const select = (e) => {
    //     console.log('选择文件：',e)
    //     console.log(imageValue1.value)
    //     // console.log(e.tempFiles[0].file)
    //     uploadApi(e.tempFilePaths[0]).then((res: any) => {
    //         if (res.code == 200) {
    //             formData.value.imageValue1 = res.data.path
    //         } else {
    //             uni.showToast({
    //                  title: res.msg,
    //                  icon: 'error',
    //                  mask: true,
    //             });
    //             imageValue1.value = {}
    //             formData.value.imageValue1 = ''
    //         }
    //     }).catch(err => {
    //         imageValue1.value = {}
    //         formData.value.imageValue1 = ''
    //     })
    // }
    // const delete1 = (e) => {
    //     console.log('删除：',e)
    //     console.log(imageValue1.value)
    //     imageValue1.value = {}
    //     formData.value.imageValue1 = ''
    // }
    // const selectImgArr = (e: any, myFileArr: any, fileArr: any) => {
    //     console.log('选择文件：',e)
    //     e.tempFiles.forEach((item: any, index: number) => {
    //         item.uri = item.url
    //         item.name = 'files'
    //     })
    //     console.log(e.tempFiles)
    //     uploadApi(e.tempFiles, true, true, true).then((res: any) => {
    //         if (res.code == 200) {
    //             res.data.forEach((item2: any, index2: number) => {
    //                 myImgArr[myFileArr].push({
    //                     uuid: e.tempFiles[index2].uuid,
    //                     path: item2.path,
    //                     url: item2.url,
    //                     name: e.tempFiles[index2].name,
    //                     extname: e.tempFiles[index2].extname,
    //                     index: index2,
    //                 })
    //             })
    //             myImgArr[fileArr] = JSON.parse(JSON.stringify(myImgArr[myFileArr]))
    //             formData.value[fileArr] = []
    //             myImgArr[myFileArr].forEach((item3: any, index3: number) => {
    //                 formData.value[fileArr].push(item3.path)
    //             })
    //             console.log(formData.value[fileArr])
    //         } else {
    //             uni.showToast({
    //                  title: res.msg,
    //                  icon: 'error',
    //                  mask: true,
    //             });
    //         }
    //     }).catch(err => {
    //         myImgArr[fileArr] = JSON.parse(JSON.stringify(myImgArr[myFileArr]))
    //     }).finally(() => {
            
    //     })
    // }
    // const deleteImgArr = (e: any, myFileArr: any, fileArr: any) => {
    //     myImgArr[myFileArr].forEach((item: any, index: number) => {
    //         console.log(item)
    //         console.log(index)
    //         if (e.tempFile.uuid == item.uuid) {
    //             myImgArr[myFileArr].splice(index, 1)
    //             console.log(myImgArr[myFileArr])
    //         }
    //     })
    //     formData.value[fileArr] = []
    //     myImgArr[myFileArr].forEach((item3: any, index3: number) => {
    //         formData.value[fileArr].push(item3.path)
    //     })
    // }
</script>

<style lang="scss" scoped>
    .home {
        background-color: #f2f2f2;
        min-height: 100vh;
    }
    .swipter {
        // height: 100rpx;
    }
    .swiper-img {
        width: 100%;
        height: 100%
    }
    :deep(.uni-forms) {
        padding: 20rpx 20rpx;
        box-sizing: border-box;
    }
    .box-1 {
        background-color: #fff;
        box-sizing: border-box;
        padding: 20rpx;
        border-radius: 20rpx;
        margin: 20rpx 0;
    }
    .money-box {
        text-align: center;
        .money-span-1 {
            color: rgb(153, 153, 153);
            font-weight: bold;
        }
        .money-span-2 {
            color: #000;
            font-weight: bold;
        }
    }
    .button-img {
        width: 100rpx;
        height: 50rpx;
        margin-right: 20rpx;
    }
    .point-box {
        display: flex;
        align-items: center;
        .point-img {
            width: 60rpx;
            height: 60rpx;
        }
        .point-box-text-1 {
            margin-left: 20rpx;
            font-weight: bold;
        }
    }
</style>
